// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/base/api/ScheduleApi'

import ComClass from '@api/ComQuery'

import ListClass from '@api/base/model/ScheduleListQueryReq'
import OneClass from '@api/base/model/ScheduleReq'
import AddClass from '@api/base/model/ScheduleOperateReq'
import BaseClass from '@api/base/model/ScheduleDto'
import CycleClass from '@api/base/model/ScheduleCycleDto'
import UserClass from '@api/base/model/ScheduleMemberDto'

const EditClass = AddClass
const DelClass = OneClass

const CLIENT = CORE.grpcCLIENT(Client)
const COM = [ComClass, 'comQuery']
const TIME_LIST = [CycleClass, 'cycles', 1]
const USER_LIST = [UserClass, 'members', 1]
const BASE = [BaseClass, 'content', null, (dto, obj) => CORE.grpcDTO(dto, obj, TIME_LIST, USER_LIST)]

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 列表 —————————————————————————————— //

  async getList(param, TIP = '查询列表') {
    const DTO = CORE.grpcDTO(ListClass, param, COM)
    const resp = await CORE.grpc(TIP, CLIENT, 'queryScheduleList', DTO)
    return [resp.comQuery.totalCount, resp.content || []]
  },

  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne({ id }, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, { ids: [id] })
    const resp = await CORE.grpc(TIP, CLIENT, 'queryScheduleDetail', DTO)
    return resp.content || {}
  },
  transOne(obj, { state: { INIT_ONE } }) {
    obj.userIds = obj.members.map((item) => item.userId).join()
    obj.cycles.forEach((item) => {
      if (!item.time) item.time = CORE.merge({}, INIT_ONE.cycles[0], { key: CORE.fileName() })
      item.scheduleTimeId = item.time.id || ''
    })
    return obj
  },

  // —————————————————————————————— 增 —————————————————————————————— //

  transAdd(one) {
    const cycles = one.cycles.map((item, i) => ({ ...item, cycleNum: i + 1 }))
    return { ...one, cycles }
  },
  async add(one, TIP = '新增') {
    const DTO = CORE.grpcDTO(AddClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'insertSchedule', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 改 —————————————————————————————— //

  transEditToAdd: true,
  async edit(one, TIP = '修改') {
    const DTO = CORE.grpcDTO(EditClass, one, BASE)
    await CORE.grpc(TIP, CLIENT, 'updateSchedule', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 删 —————————————————————————————— //

  async del({ id }, TIP = '删除') {
    const DTO = CORE.grpcDTO(DelClass, { ids: [id] })
    await CORE.grpc(TIP, CLIENT, 'deleteSchedule', DTO)
    return CORE.grpcOK(TIP)
  },
}
